package com.lemon.auth.service.impl;

import com.lemon.auth.dto.LoginFormDTO;
import com.lemon.auth.service.IAuthService;
import com.lemon.core.web.Result;
import com.lemon.redis.service.RedisService;
import com.lemon.security.dto.LoginUserDetail;
import com.lemon.security.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author 李猛
 * @datetime 2024/2/15 0:34
 * @description 类对象
 */
@Slf4j
@Service
public class AuthServiceImpl implements IAuthService {
    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisService redisService;

    @Override
    public Result<String> login(LoginFormDTO loginFormDTO) {
        log.info("login");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginFormDTO.getUsername(), loginFormDTO.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authentication)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //获取用户信息
        LoginUserDetail loginUserDetail = (LoginUserDetail) authentication.getPrincipal();

        //生成 token
        String token = JwtUtil.createToken(loginUserDetail);

        return Result.ok(token);
    }

    @Override
    public Result<String> logout() {
        log.info("logout");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取用户信息
        LoginUserDetail loginUserDetail = (LoginUserDetail) authentication.getPrincipal();
        redisService.delByKey(loginUserDetail.getUsername());
        return Result.ok();
    }
}
